package com.example.rabbitmqdemo.hellorabbitmq.pubsub;

import cn.hutool.core.util.StrUtil;
import com.example.rabbitmqdemo.hellorabbitmq.CommonUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;

@Slf4j
public class ProducerPubSub {
    static final String QUEUE_01 = "queue_01";
    static final String QUEUE_02 = "queue_02";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        ConnectionFactory factory = CommonUtil.getFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String exchangeName = "pub_sub_exchange";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT, true);
        // 定义 queue
        channel.queueDeclare(QUEUE_01, true, false, false, null);
        channel.queueDeclare(QUEUE_02, true, false, false, null);
        // 绑定
        channel.queueBind(QUEUE_01, exchangeName, "");
        channel.queueBind(QUEUE_02, exchangeName, "");
        //
        for (int i = 0; i < 10; i++) {
            String msg = StrUtil.format("fanout - {}", LocalDateTime.now());
            channel.basicPublish(exchangeName, "", null, msg.getBytes(StandardCharsets.UTF_8));
            Thread.sleep(100);
        }
        channel.close();
        connection.close();
    }
}
